/**
 * 操作相关
 */
var OPT = {
    /**
     * 注册
     */
    register: () => {
        layer.open({
            id: 'registerLayer',
            type: 1,
            title: ['注册'],
            skin: 'layui-layer-molv',
            area: '400px',
            offset: 'auto',
            content: $('#registerDialog'),
            btn: ['提交', '取消'],
            // 弹窗加载完成后回调
            success: (layero) => {
                layero.find('.layui-layer-btn').css('text-align', 'center');
                form.render();
            },
            yes: (layero, index) => {
                SOCKET.start();
            },
            cancel: (index, layero) => {
                layer.close(index)
            }
        })
    },

    /**
     * 发送聊天消息
     */
    sendMessage: () => {
        if (!SOCKET.ws || SOCKET.ws.readyState !== WebSocket.OPEN) {
            layer.msg('连接已断开，请重新连接！', {icon: 5, time: 1500});
            return false;
        }

        const messageInput = document.getElementById('messageInput');
        const message = messageInput.value.trim();
        
        if (!message) {
            layer.msg('请输入消息内容！', {icon: 5, time: 1500});
            return false;
        }

        const timestamp = new Date().getTime();

        // 发送消息
        const params = {
            type: 'chat',
            targetUid: 'all',  // 'all' 表示广播给所有人
            userId: userId,
            message: message,
            timestamp: timestamp,
            roomId: roomId
        };

        try {
            SOCKET.sendMsg(params);
            console.log('Message sent:', params);

            // 显示自己发送的消息
            OPT.appendMessage({
                userId: userId,
                message: message,
                timestamp: timestamp,
                isSelf: true
            });

            // 清空输入框
            messageInput.value = '';
        } catch (error) {
            console.error('Error sending message:', error);
            layer.msg('消息发送失败，请重试！', {icon: 2, time: 1500});
        }
    },

    /**
     * 接收聊天消息
     */
    receiveMessage: (data) => {
        console.log('Received message data:', data);
        try {
            OPT.appendMessage({
                userId: data.userId,
                message: data.message,
                timestamp: data.timestamp,
                isSelf: false
            });
        } catch (error) {
            console.error('Error processing received message:', error);
        }
    },

    /**
     * 添加消息到聊天界面
     */
    appendMessage: (data) => {
        try {
            console.log('Appending message:', data);
            const chatMessages = document.getElementById('chatMessages');
            if (!chatMessages) {
                console.error('Chat messages container not found');
                return;
            }

            const messageDiv = document.createElement('div');
            messageDiv.className = `chat-message ${data.isSelf ? 'sent' : 'received'}`;

            const messageInfo = document.createElement('div');
            messageInfo.className = 'message-info';
            messageInfo.textContent = `${data.isSelf ? '我' : data.userId} - ${new Date(data.timestamp).toLocaleTimeString()}`;

            const messageContent = document.createElement('div');
            messageContent.className = 'message-content';
            messageContent.textContent = data.message;

            messageDiv.appendChild(messageInfo);
            messageDiv.appendChild(messageContent);
            chatMessages.appendChild(messageDiv);

            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;

            // 播放消息提示音（如果需要）
            // new Audio('/static/sound/message.mp3').play().catch(e => console.log('Audio play failed'));
        } catch (error) {
            console.error('Error appending message:', error);
        }
    }
}